﻿using System;
using System.IO;
using Comdiv.QWeb.Files;
using NUnit.Framework;

namespace Comdiv.QWeb.Test.ViewEngine {
    [TestFixture]
    public class subview_and_layout_resolution_test
    {
        public class testdata
        {
            public int val;
        }
        [Action("sr.test")]
        public class testaction : IAction
        {
            [Bind]
            private int retval;
            public object Process(QWebContext context)
            {
                return new testdata { val = retval };
            }
        }

        private string code_layout =
            @"
        public partial class layoutview : BASECLS
        {
            protected override void render()
            {
                outp(""<div class='layout'>"");
                RenderChild();
                outp(""</div>"");
            }
        }";

        private string code_main =
            @"
        public partial class mainview : BASECLS
        {
            protected override void render()
            {
                outp(""<div class='outer'>"");
                sub(""child"", new {id2=46});
                outp(""</div>"");
            }
        }";

        private string code_child =
            @"
        using Comdiv.QWeb.Test.ViewEngine;
        public partial class childvide : BASECLS
        {
            [QViewBind]int val;
            [QViewBind]int id2;
            [ViewData]private subview_and_layout_resolution_test.testdata item;
            protected override void render()
            {
                outp(""<div>val:"");
                outp(val);
                outp("";id2:"");
                outp(id2);
                outp(""</div><div>itemtype:"");
                outp(item.GetType().Name);
                outp(""</div>"");
            }
        }";


        [Test]
        public void test_subview_resolution()
        {
            var reg = new QWebServiceRegistry();
            reg.FileNameResolver.Write("/qviews/layouts/test.cs", code_layout);
            reg.FileNameResolver.Write("/qviews/sr/test.cs", code_main);
            reg.FileNameResolver.Write("/qviews/sr/child.cs", code_child);
            var h = new QWebHandler(reg);
            var sw = new StringWriter();
            var ctx = new QWebContext("http://localhost/sr/test.qview.qweb").Set("retval", 45).Set("layout","test");
            ctx.Output = sw;
            h.ProcessRequest(ctx);
            Console.WriteLine(sw.ToString());
            Assert.AreEqual("<div class='layout'><div class='outer'><div>val:45;id2:46</div><div>itemtype:testdata</div></div></div>", sw.ToString());

        }
    }
}